package com.example.video.util;

import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色工具类
 *author ayan
 * 
 */
public class RoleUtils {

    // 提取并格式化角色为"[[ROLE_ADMIN]]"的格式，用来与数据库中的角色进行比较
    public static List<String> extractAndFormatRoles(Collection<? extends GrantedAuthority> authorities) {
        return authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .map(RoleUtils::formatRole)
                .collect(Collectors.toList());
    }

    // 提取角色并移除前缀和后缀,格式为[ROLE_ADMIN],用来将登录用户的角色赋值给账户，视频等
    public static List<String> extractRoles(Collection<? extends GrantedAuthority> authorities) {
        return authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .map(RoleUtils::removeRolePrefixAndSuffix)
                .collect(Collectors.toList());
    }

    // 将角色转换为数据库一致的格式
    private static String formatRole(String role) {
        return "[" + removeRolePrefixAndSuffix(role) + "]";
    }

    // 移除角色前缀和后缀
    private static String removeRolePrefixAndSuffix(String role) {
        return role.replaceAll("\\[ROLE_|\\]", "").trim();
    }
}
